import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:web_socket_channel/io.dart';
import 'package:my_flutter_app/download_with_chunk.dart';
import 'package:my_flutter_app/main.dart';
import 'package:path_provider/path_provider.dart';

import 'model/user.dart';

class HttpWebTestIndexRote extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("HttpWebTestIndexRote"),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: EdgeInsets.all(16.0),
          child: Column(
            children: <Widget>[
              RaisedButton(
                child: Text("HttpTestRoute"),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) {
                      return HttpTestRoute();
                    }),
                  );
                },
              ),
              RaisedButton(
                child: Text("DioFutureBuilderTestRoute"),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) {
                      return DioFutureBuilderTestRoute();
                    }),
                  );
                },
              ),
              RaisedButton(
                child: Text("DioDownloadChunkTestRoute"),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) {
                      return DioDownloadChunkTestRoute();
                    }),
                  );
                },
              ),
              RaisedButton(
                child: Text("WebSocketTestRoute"),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) {
                      return WebSocketTestRoute();
                    }),
                  );
                },
              ),
              RaisedButton(
                child: Text("SocketApiTestRoute"),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) {
                      return SocketApiTestRoute();
                    }),
                  );
                },
              ),
              RaisedButton(
                child: Text("JsonModelTestRoute"),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(builder: (context) {
                      return JsonModelTestRoute();
                    }),
                  );
                },
              ),

            ],
          ),
        ),
      ),
    );
  }
}

class HttpTestRoute extends StatefulWidget {
  @override
  _HttpTestRouteState createState() => _HttpTestRouteState();
}

class _HttpTestRouteState extends State<HttpTestRoute> {
  bool _loading = false;
  String _text = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('HttpTestRoute'),
      ),
      body: ConstrainedBox(
        constraints: BoxConstraints.expand(),
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              RaisedButton(
                child: Text("获取百度首页"),
                onPressed: _loading
                    ? null
                    : () async {
                        setState(() {
                          _loading = true;
                          _updateContent('正在请求...');
                        });
                        try {
                          HttpClient httpClient = new HttpClient();
                          HttpClientRequest request = await httpClient
                              .getUrl(Uri.parse("http://www.baidu.com"));
                          request.headers.add("user-agent",
                              "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_1 like Mac OS X) AppleWebKit/603.1.30 (KHTML, like Gecko) Version/10.0 Mobile/14E304 Safari/602.1");
                          HttpClientResponse response = await request.close();
                          // _text = await response.transform(utf8.decoder).join();
                          _updateContent(await response.transform(utf8.decoder).join());
                          print(MY_TAG_1 + response.headers.toString());
                          httpClient.close();
                        } catch (e) {
                          _updateContent('请求失败：$e');
                          // _text = '请求失败：$e';
                        } finally {
                          setState(() {
                            _loading = false;
                          });
                        }
                      },
              ),
              Container(
                width: MediaQuery.of(context).size.width - 50,
                child: Text(_text),
                // .replaceAll(new RegExp(r"\s"), '')
              ),
            ],
          ),
        ),
      ),
    );
  }

  _updateContent(content){
    setState(() {
      _text = content;
    });
  }
}

class DioFutureBuilderTestRoute extends StatefulWidget {
  @override
  _DioFutureBuilderTestRouteState createState() =>
      _DioFutureBuilderTestRouteState();
}

class _DioFutureBuilderTestRouteState extends State<DioFutureBuilderTestRoute> {
  Dio _dio = new Dio();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DioFutureBuilderTestRoute'),
      ),
      body: ConstrainedBox(
        constraints: BoxConstraints.expand(),
        child: Container(
          alignment: Alignment.center,
          child: FutureBuilder(
            future: _dio.get("https://api.github.com/orgs/flutterchina/repos"),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.connectionState == ConnectionState.done) {
                Response response = snapshot.data;
                if (snapshot.hasError) {
                  return Text(snapshot.error.toString());
                }
                return ListView(
                  // children: response.data.map<Widget>((e) => ListTile(title: Text(e['full_name']),)).toList(),
                  children: response.data
                      .map<Widget>((e) => ListTile(title: Text(e["full_name"])))
                      .toList(),
                );
              }
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

class DioDownloadChunkTestRoute extends StatefulWidget {
  @override
  _DioDownloadChunkTestRouteState createState() =>
      _DioDownloadChunkTestRouteState();
}

class _DioDownloadChunkTestRouteState extends State<DioDownloadChunkTestRoute> {
  var url =
      "http://dl-cdn.oray.com/sunlogin/android/SunloginClient_3.12.21.28330.apk";

  // "http://download.dcloud.net.cn/HBuilder.9.0.2.macosx_64.dmg";

  var savePath = "/example/SunloginClient_3.12.21.28330.apk";

  // "/example/HBuilder.9.0.2.macosx_64.dmg";

  var totalSavePath = '';

  String _progress = '';

  static Future<String> _getLocalDirStr() async {
    return (await getExternalStorageDirectory()).path;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('DioDownloadChunkTestRoute'),
      ),
      body: ConstrainedBox(
        constraints: BoxConstraints.expand(),
        child: Container(
          alignment: Alignment.center,
          child: Column(
            children: <Widget>[
              RaisedButton(
                child: Text('DIO_DOWNLOAD_CHUNKS'),
                onPressed: () async {
                  Future<String> getDir = _getLocalDirStr();
                  getDir.then((onValue) {
                    print(MY_TAG_1 + 'onValue= ' + onValue);
                    totalSavePath = onValue + savePath;
                    print(MY_TAG_1 + 'savePath= ' + totalSavePath);

                    downloadWithChunks(url, totalSavePath,
                        onReceiveProgress: (received, total) {
                      if (total != -1) {
                        setState(() {
                          _progress = "${(received / total * 100).floor()}%";
                        });
                      }
                    });
                  });
                },
              ),
              Container(
                width: MediaQuery.of(context).size.width - 50,
                child: Text(_progress),
                // .replaceAll(new RegExp(r"\s"), '')
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class WebSocketTestRoute extends StatefulWidget {
  @override
  _WebSocketTestRouteState createState() => _WebSocketTestRouteState();
}

class _WebSocketTestRouteState extends State<WebSocketTestRoute> {
  TextEditingController _controller = TextEditingController();

  IOWebSocketChannel _channel;

  String _text = '';

  @override
  void initState() {
    super.initState();
    _channel = IOWebSocketChannel.connect('ws://echo.websocket.org');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('WebSocketTestRoute: 回显'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(20),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Form(
                child: TextField(
                  controller: _controller,
                  decoration: InputDecoration(labelText: 'Send a message'),
                ),
              ),
              StreamBuilder(
                stream: _channel.stream,
                builder: (context, snapshot) {
                  if (snapshot.hasError) {
                    _text = 'network not connected';
                  } else if (snapshot.hasData) {
                    _text += 'echo: ' + snapshot.data + "\n";
                  }
                  return Padding(
                    padding: const EdgeInsets.symmetric(vertical: 24.0),
                    child: Text(_text),
                  );
                },
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _sendMessage,
        tooltip: 'Send message',
        child: Icon(Icons.send),
      ),
    );
  }

  void _sendMessage() {
    if (_controller.text.isNotEmpty) {
      _channel.sink.add(_controller.text);
      _controller.text = '';
    }
  }

  @override
  void dispose() {
    _channel.sink.close();
    super.dispose();
  }
}

class SocketApiTestRoute extends StatefulWidget {
  @override
  _SocketApiTestRouteState createState() => _SocketApiTestRouteState();
}

class _SocketApiTestRouteState extends State<SocketApiTestRoute> {
  bool _loading = false;
  String _response = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SocketApiTestRoute'),
      ),
      body: ConstrainedBox(
        constraints: BoxConstraints.expand(),
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              RaisedButton(
                child: Text("Socket API"),
                onPressed: _loading ? null : _request,
              ),
              Container(
                width: MediaQuery.of(context).size.width - 50,
                child: Text(_response),
                // .replaceAll(new RegExp(r"\s"), '')
              ),
            ],
          ),
        ),
      ),
    );
  }

  _request() async {
    var socket = await Socket.connect("baidu.com", 80);
    socket.writeln('GET / HTTP/1.1');
    socket.writeln('Host:baidu.com');
    socket.writeln('Connection:close');
    socket.writeln();
    await socket.flush();
    await socket.close().then((response) {
      response.cast<List<int>>().transform(utf8.decoder).listen((content) {
        print(MY_TAG_1 + "content= " + content);
        setState(() {
          _response = content;
        });
      });
    });
  }
}

class JsonModelTestRoute extends StatefulWidget {
  @override
  _JsonModelTestRouteState createState() => _JsonModelTestRouteState();
}

class _JsonModelTestRouteState extends State<JsonModelTestRoute> {
  String jsonUser = '{"name": "John Smith","email": "john@example.com"}';

  String _response = "";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('JsonModelTestRoute'),
      ),
      body: ConstrainedBox(
        constraints: BoxConstraints.expand(),
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              RaisedButton(
                child: Text("parseUser"),
                onPressed: _parseUser,
              ),
              Container(
                width: MediaQuery.of(context).size.width - 50,
                child: Text(_response),
                // .replaceAll(new RegExp(r"\s"), '')
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _parseUser() {
    Map userMap = json.decode(jsonUser);
    var user = User.fromJson(userMap);
    setState(() {
      _response = 'Howdy, ${user.name}!' +
          '\n' +
          'We sent the verification link to ${user.email}.';
    });
  }
}
